<template>
  <div id="ptouxiang" v-cloak>
    <div class="inputbox" ref="inputbox">
      <span class="jia">+</span>
      <input type="file" @change="fn" ref="touxiang" />
    </div>
    <div class="upbtn" @click="fupdate()">更新</div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      imgsrc1: "",
      userinfo: "",
    };
  },
  methods: {
    // 选择图片预览
    fn(e) {
      this.imgsrc1 = URL.createObjectURL(e.target.files[0]);
      this.$refs.inputbox.style.backgroundImage = `url(${this.imgsrc1})`;
    },
    // 更新图片
    fupdate() {
      var touxiang = this.$refs.touxiang;
      var formdata = new FormData();
      formdata.append("touxiang", touxiang.files[0]);
      this.$axios.post("/wxw/walteruser", formdata);
    },
  },
  mounted() {
    // 获取用户头像
    this.$axios.post("/wxw/wuserinfo").then((res) => {
      this.userinfo = res.data[0];
      this.imgsrc1 = this.userinfo.touxiang;
      // 图片处理
      if (this.imgsrc1.substr(0, 7) == "/public") {
        this.imgsrc1 = this.imgsrc1.replace("/public", "/wxw");
      }
      // 预览
      this.$refs.inputbox.style.backgroundImage = `url(${this.imgsrc1})`;
    });
  },
};
</script>
<style scoped="scoped">
[v-cloak] {
  display: none;
}
#ptouxiang {
  margin: 50px 0 0 100px;
  font-size: 16px;
}
.inputbox {
  width: 160px;
  height: 160px;
  text-align: center;
  line-height: 160px;
  font-size: 50px;
  border: 2px solid #ccc;
  position: relative;
  margin-bottom: 35px;
  overflow: hidden;
  color: #ccc;
}
.inputbox input {
  width: 160px;
  height: 160px;
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
}
.inputbox img {
  width: 160px;
  height: 160px;
  position: absolute;
  left: 0;
  top: 0;
  z-index: 99;
}
.upbtn {
  display: inline-block;
  background-color: #dd3915;
  color: #fff;
  padding: 7.5px 30px;
  margin: 50px 0;
  cursor: pointer;
}
.jia {
  color: rgba(200, 200, 200, 0.6);
}
</style>